import { UserLogin } from '@/api/user'
import axios from 'axios'
import { Toast } from 'react-vant'

const http = axios.create()
http.defaults.timeout = 10000

// 请求拦截
http.interceptors.request.use(
  async (config: any) => {
    const openid = localStorage.getItem('openId') || undefined

    // 强制登录
    if (!localStorage.getItem('userId')) {
      const { id, openid } = await UserLogin()
      localStorage.setItem('userId', `${id}`)
      localStorage.setItem('openId', openid)
    }

    config.headers.openid = openid || ''
    config.headers.channel = sessionStorage.getItem('channel') || ''

    return config
  },
  (error: any) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
http.interceptors.response.use(
  (response: any) => {
    const res = response.data
    if (res?.msg === '用户错误') {
      localStorage.clear()
    }
    if (res?.state === 'fail') {
      res?.msg && Toast(res?.msg)
      return Promise.reject(res)
    }

    return res
  },
  (error: any) => {
    return Promise.reject(error)
  },
)

export default http
